using FileManager.Models;
using FileManager.Services;
using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Input;
using Forms = System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;
using MessageBoxButton = System.Windows.MessageBoxButton;
using MessageBoxImage = System.Windows.MessageBoxImage;

namespace FileManager.ViewModels
{
    public class SettingsViewModel : BaseViewModel
    {
        private readonly AppSettings _settings;
        private readonly DatabaseBackupService _databaseBackupService;
        private readonly FileManagerService _fileManagerService;
        
        public event EventHandler CloseRequested;
        
        private ObservableCollection<string> _scanDirectories;
        private bool _autoScanOnStartup;
        private bool _deleteToRecycleBin;
        private bool _showNotifications;
        private int _maxScanThreads;
        private int _thumbnailSize;
        private ObservableCollection<string> _backupFiles;
        private string _selectedBackupFile;

        public SettingsViewModel(AppSettings settings, DatabaseBackupService databaseBackupService, FileManagerService fileManagerService)
        {
            _settings = settings;
            _databaseBackupService = databaseBackupService;
            _fileManagerService = fileManagerService;
            
            // 初始化属性
            ScanDirectories = new ObservableCollection<string>(_settings.ScanDirectories);
            AutoScanOnStartup = _settings.AutoScanOnStartup;
            DeleteToRecycleBin = _settings.DeleteToRecycleBin;
            ShowNotifications = _settings.ShowNotifications;
            MaxScanThreads = _settings.MaxScanThreads;
            ThumbnailSize = _settings.ThumbnailSize;
            
            // 加载备份文件列表
            LoadBackupFiles();
            
            // 初始化命令
            AddDirectoryCommand = new RelayCommand((p) => AddDirectory());
            RemoveDirectoryCommand = new RelayCommand((p) => RemoveDirectory(p as string));
            SaveSettingsCommand = new RelayCommand((p) => SaveSettings());
            SaveCommand = new RelayCommand((p) => SaveSettings());
            CancelCommand = new RelayCommand((p) => CloseRequested?.Invoke(this, EventArgs.Empty));
            CreateBackupCommand = new RelayCommand(async (p) => await _databaseBackupService.CreateBackupAsync());
            RestoreBackupCommand = new RelayCommand(async (p) => 
            {
                if (SelectedBackupFile != null)
                {
                    await _databaseBackupService.RestoreBackupAsync(SelectedBackupFile);
                    LoadBackupFiles();
                }
            });
            DeleteBackupCommand = new RelayCommand(async (p) => 
            {
                if (SelectedBackupFile != null)
                {
                    if (MessageBox.Show("确定要删除此备份吗？", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        await _databaseBackupService.DeleteBackupAsync(SelectedBackupFile);
                        LoadBackupFiles();
                    }
                }
            });
        }

        #region 属性

        public ObservableCollection<string> ScanDirectories
        {
            get => _scanDirectories;
            set => SetProperty(ref _scanDirectories, value);
        }

        public bool AutoScanOnStartup
        {
            get => _autoScanOnStartup;
            set => SetProperty(ref _autoScanOnStartup, value);
        }

        public bool DeleteToRecycleBin
        {
            get => _deleteToRecycleBin;
            set => SetProperty(ref _deleteToRecycleBin, value);
        }

        public bool ShowNotifications
        {
            get => _showNotifications;
            set => SetProperty(ref _showNotifications, value);
        }

        public int MaxScanThreads
        {
            get => _maxScanThreads;
            set => SetProperty(ref _maxScanThreads, value);
        }

        public int ThumbnailSize
        {
            get => _thumbnailSize;
            set => SetProperty(ref _thumbnailSize, value);
        }

        public ObservableCollection<string> BackupFiles
        {
            get => _backupFiles;
            set => SetProperty(ref _backupFiles, value);
        }

        public string SelectedBackupFile
        {
            get => _selectedBackupFile;
            set => SetProperty(ref _selectedBackupFile, value);
        }

        #endregion

        #region 命令

        public ICommand AddDirectoryCommand { get; }
        public ICommand RemoveDirectoryCommand { get; }
        public ICommand SaveSettingsCommand { get; }
        public ICommand SaveCommand { get; }
        public ICommand CancelCommand { get; }
        public ICommand CreateBackupCommand { get; }
        public ICommand RestoreBackupCommand { get; }
        public ICommand DeleteBackupCommand { get; }

        #endregion

        #region 方法

        private void AddDirectory()
        {
            var folderDialog = new System.Windows.Forms.FolderBrowserDialog
            {
                Description = "选择要扫描的文件夹",
                ShowNewFolderButton = false
            };

            if (folderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string selectedPath = folderDialog.SelectedPath;
                if (!ScanDirectories.Contains(selectedPath))
                {
                    ScanDirectories.Add(selectedPath);
                }
            }
        }

        private void RemoveDirectory(string directory)
        {
            if (directory != null && ScanDirectories.Contains(directory))
            {
                ScanDirectories.Remove(directory);
            }
        }

        private void SaveSettings()
        {
            _settings.ScanDirectories = new System.Collections.Generic.List<string>(ScanDirectories);
            _settings.AutoScanOnStartup = AutoScanOnStartup;
            _settings.DeleteToRecycleBin = DeleteToRecycleBin;
            _settings.ShowNotifications = ShowNotifications;
            _settings.MaxScanThreads = MaxScanThreads;
            _settings.ThumbnailSize = ThumbnailSize;
            
            _settings.Save();
            
            MessageBox.Show("设置已保存", "保存成功", MessageBoxButton.OK, MessageBoxImage.Information);
            CloseRequested?.Invoke(this, EventArgs.Empty);
        }

        private void LoadBackupFiles()
        {
            var backups = _databaseBackupService.GetAvailableBackups();
            BackupFiles = new ObservableCollection<string>(backups);
        }

        #endregion
    }
}